using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;

namespace DailyTransaction
{
    public partial class frmDailyChecking : Form
    {
        private BAO bao = new BAO();
        private BAO_Rcpt bao_rcpt = new BAO_Rcpt();
        DataTable tblUnsub = null;
        DataTable tblSub = null;
        public int role;
        private string currVAT = "";
        private ArrayList rIdxs = new ArrayList();
        private ArrayList colIdxs = new ArrayList();

        private DAO_CMSI dao_cmsi = new DAO_CMSI();
        string pmt_rev = "";
        

        public frmDailyChecking()
        {
            InitializeComponent();
            txtCMSnber.Enabled = false;
            /*cbcol.HeaderText = "pmnt_mode_revised";
            cbcol.DataSource = bao.get_Paymode_revised();
            cbcol.DisplayMember = "kind_pment";
            cbcol.ValueMember = "kind_pment";
            cbcol.Name = "pmnt_mode_revised";
            cbcol.ReadOnly = false;
            //cbcol.DisplayIndex = 3;
            cbcol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            txtcol.HeaderText = "VAT_number_revised";
            txtcol.Name = "VAT_number_revised";
            txtcol.ReadOnly = false;*/
            
            
        }
        
        public void setupPrivilege()
        {
            switch (role)
            {
                case 1:
                    dtgSubmit.ReadOnly = false;
                    btnCommit.Enabled = true;
                    break;
                case 2:
                    dtgSubmit.ReadOnly = false;
                    btnCommit.Enabled = true;
                    break;
            }

        }
        private void frmDailyChecking_Load(object sender, EventArgs e)
        {
            setupPrivilege();
            cboVATCenter.DataSource = bao.get_qVAT_Center();
            cboVATCenter.DisplayMember = "VAT Center";
            cboVATCenter.ValueMember = cboVATCenter.DisplayMember;

            cbPayMode.DataSource = bao.get_Paymode();
            cbPayMode.DisplayMember = "pay_mode";
            cbPayMode.ValueMember = cbPayMode.DisplayMember;

            dtgUnsubmit.DataSource = bindingSource1;
            dtgSubmit.DataSource = bindingSource2;
            //run_batch_data();
            initdata();
            //dtgUnsubmit.Columns[0].ReadOnly = true;
            set_ReadOnly();
        }

        private void set_ReadOnly()
        {
            foreach (DataGridViewColumn col in dtgUnsubmit.Columns)
            {
                if (col.Name != "pmnt_mode_revised" && col.Name!= "Receptionist" && col.Name!="upd_remark")
                    col.ReadOnly = true;
            }

            foreach (DataGridViewColumn col in dtgSubmit.Columns)
            {
                if (col.Name != "pmnt_mode_revised" && col.Name != "VAT_number_revised" && col.Name != "Received" && col.Name != "Receptionist" && col.Name != "upd_remark")
                {
                    col.ReadOnly = true;
                }
            }
            dtgUnsubmit.Columns["CMS_number"].Frozen = true;
            dtgUnsubmit.Columns["VAT_number"].Frozen = true;
            dtgSubmit.Columns["CMS_number"].Frozen = true;
            dtgSubmit.Columns["VAT_number"].Frozen = true;
        }
        
        public void initdata()
        {
            string date_type = "";
            if (rbtInvoice.Checked == true)
                date_type = "date_visit";
            else if (rbtTransaction.Checked == true)
                date_type = "UPD_Payment_Date";
            else if (rbtReceived.Checked == true)
                date_type = "Received_Date";
            string pmt_mode = cbPayMode.SelectedValue.ToString();
            if (cbPayMode.SelectedValue == null || cbPayMode.SelectedValue.ToString().Trim() == "")
                return;
            if (cboVATCenter.SelectedValue == null || cboVATCenter.SelectedValue.ToString().Trim() == "")
                return;
            load_Data_Unsubmitted(pmt_mode, cboVATCenter.SelectedValue.ToString(),
                                            dtpFrom.Value.ToShortDateString(), 
                                            dtpTo.Value.ToShortDateString());
            load_Data_Submmited( pmt_mode, cboVATCenter.SelectedValue.ToString(),
                                            dtpReceivedDate.Value.ToShortDateString(), 
                                            dtpReceivedDate.Value.ToShortDateString());
            //if (tblUnsub != null)
            //    tblUnsub.Clear();
            //if (tblSub != null)
            //    tblSub.Clear();            
            alignColumnNumber();
            bindingSource1.DataSource = tblUnsub;
            bindingSource2.DataSource = tblSub;
            
        }
        private void alignColumnNumber()
        {
            dtgUnsubmit.Columns["CMS_number"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtgUnsubmit.Columns["total_proc"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtgUnsubmit.Columns["total_phar"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtgUnsubmit.Columns["total_amt"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtgUnsubmit.Columns["total_amt_vnd"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            //dtgUnsubmit.Columns["total_amt_vnd"].
            
        }
        private void load_Data_Submmited(string pmnt_mode, string vat_center, string fdate, string tdate)
        {
            tblSub = bao.get_Invoices_Submitted("Received_Date", pmnt_mode,
                                                 vat_center,
                                                 fdate,
                                                 tdate);
            bindingSource2.DataSource = tblSub;
            bindingSource2.ResetBindings(false);
            //dtgSubmit.Columns["VAT_number_revised"].ReadOnly = false;
            //dtgSubmit.Columns["pmnt_mode_revised"].ReadOnly = false;            
            dtgSubmit.Columns["upd_payment_date"].Visible = false;
            dtgSubmit.Columns["upd_SUN_Import_date"].Visible = false;

        }
        private void load_Data_Unsubmitted(string pmnt_mode, string vat_center, string fdate, string tdate)
        {            
            tblUnsub = bao.get_Invoices_unSubmitted("date_visit",
                                                    pmnt_mode,
                                                    vat_center,
                                                    fdate,
                                                    tdate);
            //tblSub = bao.get_Invoices_unSubmitted(date_type, 
            //                                        pmt_mode, 
            //                                        cboVATCenter.SelectedValue.ToString(), 
            //                                        dtpFrom.Value.ToShortDateString(), 
            //                                        dtpTo.Value.ToShortDateString());
            //tblSub.Clear();
            bindingSource1.DataSource = tblUnsub;
            //bindingSource2.DataSource = tblSub;
            if (tblUnsub.Rows.Count > 0)
            {
                //dtgUnsubmit.Columns["total_amt_vnd"]
                dtgUnsubmit.Columns["VAT_number_revised"].Visible = false;
                //dtgUnsubmit.Columns["pmnt_mode_revised"].Visible = false;
                dtgUnsubmit.Columns["upd_payment_date"].Visible = false;
                dtgUnsubmit.Columns["upd_SUN_Import_date"].Visible = false;                
            }
        }
       
        //private void AddHeader()
        //{
        //    dtgUnsubmit.Columns.Add("0", "Date visit");
        //    dtgUnsubmit.Columns.Add("1", "CMS_number");
        //    dtgUnsubmit.Columns.Add("2", "Pay mode");
        //    dtgUnsubmit.Columns.Add("3", "pmod_revised");
        //    dtgUnsubmit.Columns.Add("4", "Total proc");
        //    dtgUnsubmit.Columns.Add("5", "Total phar");
        //    dtgUnsubmit.Columns.Add("6", "Total amt");
        //    dtgUnsubmit.Columns.Add("7", "Total amt VND");
        //    dtgUnsubmit.Columns.Add("8", "Rate curr");
        //    dtgUnsubmit.Columns.Add("9", "Received");
        //    dtgUnsubmit.Columns.Add("10", "Received date");

        //    dtgUnsubmit.Columns[6].Width = 90;
        //    dtgUnsubmit.Columns[7].Width = 120;                        
        //}

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();           
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
         //   getListInvoicesUnsubmitted();
            
            if (cbPayMode.SelectedValue == null || cbPayMode.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("Please choose a payment mode!");
                cbPayMode.Focus();
                return;
            }

            if (cboVATCenter.SelectedValue == null || cboVATCenter.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("Please choose a VAT Center!");
                cboVATCenter.Focus();
                return;
            }

            if (rbtInvoice.Checked == true || rbtTransaction.Checked == true)
            {
                load_Data_Unsubmitted(cbPayMode.SelectedValue.ToString(), cboVATCenter.SelectedValue.ToString(),
                                      dtpFrom.Value.ToShortDateString(), dtpTo.Value.ToShortDateString());
                //load_Data_Submmited(cbPayMode.SelectedValue.ToString(), cboVATCenter.SelectedValue.ToString(),
                //                    dtpReceivedDate.Value.ToShortDateString(), dtpReceivedDate.Value.ToShortDateString());
                if (tblSub != null && tblSub.Rows.Count > 0)
                    tblSub.Clear();
                txtInvnber.Focus();
            }
            else if (rbtReceived.Checked == true)
            {
                //if (tblUnsub != null)
                //    tblUnsub.Clear();
                               
                load_Data_Submmited(cbPayMode.SelectedValue.ToString(), 
                                    cboVATCenter.SelectedValue.ToString(),
                                    dtpFrom.Value.ToShortDateString(),
                                    dtpTo.Value.ToShortDateString());                         
            }
        }
    
        private void btnCommit_Click(object sender, EventArgs e)
        {
            bool flag = true;
            int num_received = 0;
            int num_unreceived = 0;
            int num_VAT00000 = 0;
            if (rbtInvoice.Checked == true)
            {
               // date_type = "date_visit";
                try
                {
                    num_received = update_invoices_received();
                    //added on 16/7/2009
                    //update invoices have VAT_NUM = 00000 and pay total = 0
                    num_VAT00000 = bao.Update_Received_VAT00000_DailyTrans(dtpFrom.Value.ToShortDateString(),
                                                            dtpTo.Value.ToShortDateString());
                    //end
                    load_Data_Submmited(cbPayMode.SelectedValue.ToString(), cboVATCenter.SelectedValue.ToString(),
                                            dtpReceivedDate.Value.ToShortDateString(),
                                            dtpReceivedDate.Value.ToShortDateString());
                    tblSub.Clear();
                    MessageBox.Show("Updated " + num_received.ToString() + " invoice(s) and " + num_VAT00000.ToString() + " invoice(s) VAT00000");
                }
                catch (Exception ex)
                {
                    flag = false;
                    MessageBox.Show(ex.Message);
                }
            }
            else if (rbtTransaction.Checked == true)
            {
                //date_type = "UPD_Payment_Date";
                ;
               
            }
            else if (rbtReceived.Checked == true)
            {
                //date_type = "Received_Date";

                try
                {
                    rIdxs.Sort();
                    num_unreceived = update_invoices_received_modified();
                    //num_received = update_invoices_received();
                    load_Data_Submmited(cbPayMode.SelectedValue.ToString(), cboVATCenter.SelectedValue.ToString(),
                                            dtpReceivedDate.Value.ToShortDateString(),
                                            dtpReceivedDate.Value.ToShortDateString());
                    MessageBox.Show("Updated " + num_unreceived.ToString() + " invoice(s) modified ");
                   
                    
                }
                catch (Exception ex)
                {
                    flag = false;
                    MessageBox.Show(ex.Message );
                }
            }
            //string pmt_mode = cbPayMode.SelectedValue.ToString();
            
            
            if (flag == true)
            {
               // tblSub.Clear();
                //load_Data_Unsubmitted();

                bindingSource2.ResetBindings(false);
                txtCMSnber.Text = "";
                txtInvnber.Text = "";
                txtInvnber.Focus();
            }
        }
     
        //update recived invoices that modified payment mode
        private int update_invoices_received_modified()
        {
            string curr_vat_num = "";            
            int num_pmnt_revised = 0;
            string pay_revised = "";
            string vat_nber_revised = "";
            string rcpt_name = "";
            string upd_remark = "";
            int rslt = 0;
            string received_date="";

            foreach (DataGridViewRow r in dtgSubmit.Rows)                                   
            {
                //if (r.Cells["Received"].Value.ToString() == "" || Convert.ToBoolean(r.Cells["Received"].Value) == false)
                if (rIdxs.IndexOf(r.Index)!=-1)
                {
                    curr_vat_num = r.Cells["VAT_number"].Value.ToString();
                    pay_revised = r.Cells["pmnt_mode_revised"].Value != null ? r.Cells["pmnt_mode_revised"].Value.ToString() : "";
                    vat_nber_revised = r.Cells["VAT_number_revised"].Value != null ? r.Cells["VAT_number_revised"].Value.ToString() : "";
                    rcpt_name = r.Cells["Receptionist"].Value != null ? r.Cells["Receptionist"].Value.ToString() : " ";
                    upd_remark = r.Cells["upd_remark"].Value != null ? r.Cells["upd_remark"].Value.ToString() : " ";
                    received_date = DateTime.Parse(r.Cells["Received_Date"].Value.ToString()).ToShortDateString();
                    try
                    {
                        rslt += bao.update_DB(r.Cells["date_visit"].Value.ToString(),
                                       r.Cells["CMS_number"].Value.ToString(),
                                       vat_nber_revised,
                                       Convert.ToInt32(r.Cells["Received"].Value),
                                       pay_revised,                            
                                       r.Cells["Received_Date"].Value.ToString(),
                                       rcpt_name,
                                       upd_remark);
                        //dtpReceivedDate.Value.ToShortDateString());                       

                    }
                    catch (Exception ex)
                    {
                        return rslt;
                    }

                    //Added on 8/7/2009
                    // update payment mode revised for CMS_interface
                    if (pay_revised.Trim().Equals("") == false || vat_nber_revised.Trim().Equals("") == false)
                    {
                        num_pmnt_revised += dao_cmsi.update_pmnt_mode_CMSI(r.Cells["date_visit"].Value.ToString(),
                                        r.Cells["CMS_number"].Value.ToString(),
                                        vat_nber_revised,
                                        pay_revised, received_date);
                        //update payment_mode for new_revenue in sqlserver 
                        bao.Update_pmnt_mode_NEW_REVENUE(r.Cells["date_visit"].Value.ToString(),
                                        r.Cells["CMS_number"].Value.ToString(),
                                        vat_nber_revised,
                                        pay_revised, received_date);
                    }
                    //end

                }
            }
            MessageBox.Show("Updated " + num_pmnt_revised.ToString() + " paymentmode revised(s)!");
            //string tt = "";
            //for (int i = 0; i < rIdxs.Count; i++)
            //    tt += "_" + rIdxs[i].ToString();
            //MessageBox.Show(tt);
            
            return rslt;
        }

        //update invoices received 
        public int update_invoices_received()
        {
            string curr_vat_num = "";
            int cupd = 0;
            int num_pmnt_revised = 0;
            string pay_revised="";
            string vat_nber_revised = "";
            string rcpt_name = "";
            string upd_remark = "";

            string received_date = "";
            foreach (DataGridViewRow r in dtgSubmit.Rows)
            {
               // if (Convert.ToBoolean(r.Cells["Received"].Value) == true)
                //{
                curr_vat_num = r.Cells["VAT_number"].Value.ToString();
                pay_revised = r.Cells["pmnt_mode_revised"].Value != null ? r.Cells["pmnt_mode_revised"].Value.ToString() : "";
                vat_nber_revised = r.Cells["VAT_number_revised"].Value != null ? r.Cells["VAT_number_revised"].Value.ToString() : "";
                rcpt_name = r.Cells["Receptionist"].Value != null ? r.Cells["Receptionist"].Value.ToString(): " ";
                upd_remark = r.Cells["upd_remark"].Value != null ? r.Cells["upd_remark"].Value.ToString() : " ";
                //int isReceived = Convert.ToInt32(r.Cells["Received"].Value);
                //string dateV = r.Cells["date_visit"].Value.ToString();
                //string cmsnum = r.Cells["CMS_number"].Value.ToString();
                //string dateR = r.Cells["Received_Date"].Value.ToString();
                received_date = DateTime.Parse(r.Cells["Received_Date"].Value.ToString()).ToShortDateString();
                cupd += bao.update_DB(r.Cells["date_visit"].Value.ToString(),
                               r.Cells["CMS_number"].Value.ToString(),
                               vat_nber_revised,
                               Convert.ToInt32(r.Cells["Received"].Value),
                               pay_revised,
                               r.Cells["Received_Date"].Value.ToString(),
                               rcpt_name,
                               upd_remark);                 
                //dtpReceivedDate.Value.ToShortDateString());                       
        //    } 

                //Added on 8/7/2009
                //update payment mode and vat_number revised for CMS_interface
                if (pay_revised.Trim().Equals("")==false || vat_nber_revised.Trim().Equals("")==false)
                {
                    //update payment_mode for new_revenue in cms_interface 
                    num_pmnt_revised += dao_cmsi.update_pmnt_mode_CMSI(r.Cells["date_visit"].Value.ToString(),
                                    r.Cells["CMS_number"].Value.ToString(),
                                    vat_nber_revised,
                                    pay_revised, received_date);
                    //update payment_mode for new_revenue in sqlserver 
                    bao.Update_pmnt_mode_NEW_REVENUE(r.Cells["date_visit"].Value.ToString(),
                                    r.Cells["CMS_number"].Value.ToString(),
                                    vat_nber_revised,
                                    pay_revised, received_date);
                }
                    //end
            }

            MessageBox.Show("Updated " + num_pmnt_revised.ToString() + " paymentmode revised(s)!");
            return cupd;
        }
        private void txtInvnber_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter)
            //{
            //    string VAT_number = "";
            //    //VAT_number = cboVATCenter.SelectedValue.ToString() + txtInvnber.Text.Trim();
            //    if (cboVATCenter.SelectedValue.ToString() != "*ALL")
            //    {
            //        VAT_number = cboVATCenter.SelectedValue.ToString() + txtInvnber.Text.Trim();
            //    }
            //    else
            //    {
            //        VAT_number = getVATnumber(txtInvnber.Text.Trim(), txtInvnber.Text.Trim().Length);
            //    }
            //    currVAT = VAT_number;
            //    int rnum = bao.check_VAT_number(VAT_number);
            //    if (rnum > 1)
            //    {
            //        //lblMsg.Text = "More than 1 invoice have the same VAT_number!";
            //        MessageBox.Show("More than 1 invoice have the same VAT_number!");
            //        txtCMSnber.Enabled = true;
            //        txtCMSnber.Text = "";
            //        txtCMSnber.Focus();
            //        return;
            //    }
            //    tick_row(VAT_number, " ");                
            //}
            //txtInvnber.Focus();
        }

        private void txtInvnber_TextChanged(object sender, EventArgs e)
        {            
            string VAT_number = "";
            if (txtInvnber.TextLength >=5 && txtInvnber.Text.Trim() != "")
            {
                
                if (cboVATCenter.SelectedValue.ToString() != "*ALL")
                {
                    VAT_number = cboVATCenter.SelectedValue.ToString() + txtInvnber.Text.Trim();                    
                }
                else
                {
                    VAT_number = getVATnumber(txtInvnber.Text.Trim(), txtInvnber.Text.Trim().Length);                   
                }
               
                //added 2/7/2009
                currVAT = VAT_number;
                //end
                int rnum = bao.check_VAT_number(VAT_number);

                if (rnum >= 1)
                {
                    //check if invoice is in the date range
                    if (checkOnDateRange(VAT_number) == false)
                    {
                        MessageBox.Show("VAT# is existed but not in date range selected!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        MessageBox.Show("VAT# is existed but not in date range selected!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtCMSnber.Enabled = false;
                        txtCMSnber.Text = "";
                        txtCMSnber.Focus();
                        return;
                    }
                }
                if (rnum > 1)
                {
                    //lblMsg.Text = "More than 1 invoice have the same VAT_number!";
                    txtCMSnber.Text = "";
                    DialogResult rslt = MessageBox.Show("More than 1 invoice have the same VAT_number!","Warning!",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button3);
                    rslt = MessageBox.Show("More than 1 invoice have the same VAT_number!", "Warning!", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3);                                             

                    if (rslt == DialogResult.OK)
                    {
                        txtCMSnber.Enabled = true;
                        txtCMSnber.Text = "";
                        txtCMSnber.Focus();
                        return;
                    }
                    else //if (rr == DialogResult.Cancel)
                    {
                        txtCMSnber.Enabled = false;
                        txtInvnber.Text = "";
                        txtInvnber.Focus();
                        return;
                    }
                }
                else if (rnum < 1)
                {
                    //lblMsg.Text = "VAT# not exists!";
                    MessageBox.Show("VAT# not exists or cannot find!","Warning!",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    txtCMSnber.Enabled = true;
                    txtCMSnber.Text = "";
                    txtCMSnber.Focus();
                    return;
                }
                
                // mark received for invoice
                tick_row(VAT_number," ");                           
            }
            
            txtInvnber.Focus();
        }        

        private bool checkOnDateRange(string VAT_number)
        {
            foreach (DataGridViewRow r in dtgUnsubmit.Rows)
            {
                string VAT_num = r.Cells["VAT_number"].Value.ToString();
                if (VAT_number.Trim() == VAT_num.Trim())
                    return true;
            }
            return false;
        }
        private string getVATnumber(string pVATnum, int lVATnum)
        {
            foreach (DataGridViewRow r in dtgUnsubmit.Rows)
            {
                string VAT_number = r.Cells["VAT_number"].Value.ToString();
                if (VAT_number.Substring(VAT_number.Length - lVATnum) == pVATnum)
                    return VAT_number;
            }
            return "";
        }
        public void tick_row(string VAT_number,string CMS_number)
        {            
            int flag = 0;
            DataRow rr = null;
            try
            {
                foreach (DataRow row in tblUnsub.Rows)
                {
                    if (CMS_number.Trim() != "")
                    {
                        //modified on 8/7/2009
                        //if (row["VAT_number"].ToString() == VAT_number && row["CMS_number"].ToString() == CMS_number)//txtInvnber.Text.Trim())
                        //end
                        if (row["CMS_number"].ToString() == CMS_number)
                        {
                            rr = row;
                            DataRow nrow = tblSub.NewRow();
                            
                            for (int i = 0; i < tblUnsub.Columns.Count - 1; i++)
                            {
                                nrow[i] = row[i];
                            }                            
                            tblSub.Rows.Add(nrow);                            
                            flag = 1;                            
                            break;                        
                        }
                    }
                    else
                        if (row["VAT_number"].ToString() == VAT_number)//txtInvnber.Text.Trim())
                        {
                            rr = row;
                            DataRow nrow = tblSub.NewRow();
                            for (int i = 0; i < tblUnsub.Columns.Count - 1; i++)
                            {
                                nrow[i] = row[i];
                            }
                            tblSub.Rows.Add(nrow);
                            flag = 1;
                            break;                        
                        }
                }
                //mark_check(txtInvnber.Text);
                mark_check(VAT_number,CMS_number);
            }
            catch (Exception ex)
            {
                flag = 0;
            }
            if (flag == 1 && tblUnsub != null && tblUnsub.Rows.Count > 0)
            {
                tblUnsub.Rows.Remove(rr);
                tblUnsub.AcceptChanges();
                //DataTable tem = tblUnsub.GetChanges(DataRowState.Deleted);
            }            
            bindingSource1.ResetBindings(false);
            bindingSource2.ResetBindings(false);
            txtInvnber.SelectAll();
        }

        public void mark_check(string vat_nber, string cms_nber)
        {
            //foreach (DataRow row in tblUnsub.Rows)
            try
            {
                foreach (DataGridViewRow r in dtgSubmit.Rows)
                {
                    //if (r.Cells["VAT_number"].Value.ToString() == txtInvnber.Text.Trim())
                    if (cms_nber.Trim() != "")
                    {
                        if (r.Cells["CMS_number"].Value.ToString() == cms_nber)
                        {
                            r.Cells["Received"].Value = true;
                            r.Cells["Received_Date"].Value = dtpReceivedDate.Value.ToShortDateString();
                            dtgSubmit.CurrentCell = r.Cells[0];
                            break;
                        }
                    }
                    else
                        if (r.Cells["VAT_number"].Value.ToString() == vat_nber)
                        {
                            r.Cells["Received"].Value = true;
                            r.Cells["Received_Date"].Value = dtpReceivedDate.Value.ToShortDateString();
                            dtgSubmit.CurrentCell = r.Cells[0];
                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void txtCMSnber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //string VAT_number = "";                
                if (txtCMSnber.TextLength >= 5 && txtInvnber.Text.Trim() != "")
                {
                    foreach (DataGridViewRow row in dtgUnsubmit.Rows)
                    {
                        if (row.Cells["CMS_number"].Value.ToString() == txtCMSnber.Text.Trim())
                        {
                            //commented on 2/7/2009
                            //VAT_number = cboVATCenter.SelectedValue.ToString() + txtInvnber.Text.Trim();
                            //replace VAT_number by currVAT
                            //end
                            tick_row(currVAT, txtCMSnber.Text);
                            txtCMSnber.Enabled = false;
                            //lblMsg.Text = "";
                            txtInvnber.Focus();
                            return;
                        }
                    }
                    MessageBox.Show("VAT# and CMS# not exists in system!");
                    //txtCMSnber.Focus();                    
                    txtInvnber.Focus();
                    txtInvnber.SelectAll();
                }
            }
        }

        public bool IsComboBoxColumn(int colInx)
        {
            DataGridViewColumn comboBoxCol = dtgSubmit.Columns["pmnt_mode_revised"];
            if (dtgSubmit.Columns[colInx] == comboBoxCol)
                return true;
            comboBoxCol = dtgSubmit.Columns["Receptionist"];
            if (dtgSubmit.Columns[colInx] == comboBoxCol)
                return true;
            return false;
        }

        private bool IsTextBoxColumn(int colInx)
        {
            DataGridViewColumn textBoxCol = dtgSubmit.Columns["VAT_number_revised"];
            if (dtgSubmit.Columns[colInx] == textBoxCol)
                return true;
            return false;

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (cboVATCenter.SelectedValue.ToString() == "*ALL")
            {
                MessageBox.Show("Please choose VAT center!","Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                cboVATCenter.Focus();
                return;
            }
            if (txtStartnum.Text.Trim() == "")
            {
                MessageBox.Show("Please input start number!");
                txtStartnum.Focus();
                return;
            }
            else if (bao.isNumeric(txtStartnum.Text.Trim()) == false)
            {
                MessageBox.Show("Starting number must be number!");
                txtStartnum.Focus();
                return;
            }

            if (txtEndnum.Text.Trim() == "")
            {
                MessageBox.Show("Please input ending number!");
                txtEndnum.Focus();
                return;
            }
            else if (bao.isNumeric(txtEndnum.Text.Trim()) == false)
            {
                MessageBox.Show("Ending number must be number!");
                txtEndnum.Focus();
                return;
            }

            int r = bao.InsertIntoDailyTransReport(txtStartnum.Text.Trim(), txtEndnum.Text.Trim(), cboVATCenter.SelectedValue.ToString());
            MessageBox.Show("Inserted " + r.ToString() + " record(s)");
        }
                      
        private void btnSaveUnreceived_Click(object sender, EventArgs e)
        {
            int num_unreceived = 0;
            try
            {
                num_unreceived = update_pmnt_mode_unreceived();
                MessageBox.Show("Updated " + num_unreceived.ToString() + " invoice(s)");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //update payment mode for invoice isn't received
        private int update_pmnt_mode_unreceived()
        {
            string curr_vat_num = "";
            int rslt = 0;
            string pay_revised = "";
            string received_date = "";
            string rcpt_name = "";
            string upd_remark = "";
            int isReceived = 0;
            int num_pmnt_revised = 0;//update for CMS Interface
            foreach (DataGridViewRow r in dtgUnsubmit.Rows)
            {
                if (r.Cells["pmnt_mode_revised"].Value.ToString().Equals("")==false)
                {
                    curr_vat_num = r.Cells["VAT_number"].Value.ToString();
                    pay_revised = r.Cells["pmnt_mode_revised"].Value.ToString();// != "" ? r.Cells["pmnt_mode_revised"].Value.ToString() : "";                    
                    received_date = r.Cells["Received_Date"].Value.ToString() == "" ? "1/1/2200" : r.Cells["Received_Date"].Value.ToString();                    
                    rcpt_name = r.Cells["Receptionist"].Value.ToString();
                    upd_remark = r.Cells["upd_remark"].Value != null ? r.Cells["upd_remark"].Value.ToString() : " ";
                    try
                    {
                        bao.update_DB(r.Cells["date_visit"].Value.ToString(),
                                       r.Cells["CMS_number"].Value.ToString(),
                                      r.Cells["VAT_number_revised"].Value.ToString(),
                            // Convert.ToInt32(r.Cells["received"].Value),
                                       isReceived,
                                       pay_revised,
                            // r.Cells["Received_Date"].Value.ToString());
                                      received_date,
                                      rcpt_name,
                                      upd_remark);
                        //dtpReceivedDate.Value.ToShortDateString());                       
                        //Added on 10/7/2009
                        num_pmnt_revised += dao_cmsi.update_pmnt_mode_CMSI(r.Cells["date_visit"].Value.ToString(),
                                        r.Cells["CMS_number"].Value.ToString(),
                                        "",
                                        pay_revised, r.Cells["date_visit"].Value.ToString());
                        //update payment_mode for new_revenue in sqlserver 
                        bao.Update_pmnt_mode_NEW_REVENUE(r.Cells["date_visit"].Value.ToString(),
                                        r.Cells["CMS_number"].Value.ToString(),
                                        "",
                                        pay_revised, r.Cells["date_visit"].Value.ToString());
                        //end

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return rslt;
                    }
                    rslt += 1;                    
                }                
            }
            MessageBox.Show("Updated payment_mode revised for " + num_pmnt_revised + " invoice(s) in CMI! ");
            return rslt;
        }

        private void lnkInputRecpt_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            frmRcpt frmrcpt = new frmRcpt();
            frmrcpt.ShowDialog();
        }

        private void dtgSubmit_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgSubmit.RowCount == 0)
                return;

            DataGridViewColumn curCol = dtgSubmit.CurrentCell.OwningColumn;
            if (curCol.Name == "VAT_number_revised")
            {
                DataGridViewTextBoxCell currCell = (DataGridViewTextBoxCell)dtgSubmit.CurrentCell;
                if (bao.isNumeric(currCell.Value.ToString())==false)
                {
                    MessageBox.Show("Please input numerical character!","Warning!",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    currCell.Value = "";
                    currCell.Selected = true;
                    //dtgSubmit.CurrentCell = currCell;
                }
                
            }
            /*else if (curCol.Name == "pmnt_mode_revised")
            {
                if (dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].Value.ToString().Trim() == "")
                {
                    DataGridViewTextBoxCell txtcell = new DataGridViewTextBoxCell();
                    //txtcell.MaxInputLength = 5;
                    txtcell.Value = pmt_rev;
                    dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"] = txtcell;
                    dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].ReadOnly = false;
                    dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].Value = pmt_rev;

                    //dataGridView1.CurrentRow.Cells["pmnt_mode_revised"].Value = pmt_rev;
                    dtgSubmit.RefreshEdit();
                    pmt_rev = "";
                }
            }*/
            if (rIdxs.IndexOf(e.RowIndex) == -1)
                rIdxs.Add(e.RowIndex);
          
        }

        private void dtgUnsubmit_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgUnsubmit.RowCount == 0)
                return;

            DataGridViewColumn curCol = dtgUnsubmit.CurrentCell.OwningColumn;
            if (curCol.Name == "pmnt_mode_revised")
            {
                if (dtgUnsubmit.CurrentRow.Cells["pmnt_mode_revised"].Value.ToString().Trim() == "")                                
                {
                    DataGridViewTextBoxCell txtcell = new DataGridViewTextBoxCell();
                    //txtcell.MaxInputLength = 5;
                    txtcell.Value = pmt_rev;
                    dtgUnsubmit.CurrentRow.Cells["pmnt_mode_revised"] = txtcell;
                    dtgUnsubmit.CurrentRow.Cells["pmnt_mode_revised"].ReadOnly = false;
                    dtgUnsubmit.CurrentRow.Cells["pmnt_mode_revised"].Value = pmt_rev;

                    //dataGridView1.CurrentRow.Cells["pmnt_mode_revised"].Value = pmt_rev;
                    dtgUnsubmit.RefreshEdit();
                    pmt_rev = "";
                }
            }
        }

        private void dtgUnsubmit_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewColumn curCol = dtgUnsubmit.CurrentCell.OwningColumn;
            if (curCol.Name == "pmnt_mode_revised")
            {
                if (pmt_rev == "")
                {
                    pmt_rev = dtgUnsubmit.CurrentRow.Cells["pmnt_mode_revised"].Value.ToString();
                }
                dtgUnsubmit.CurrentRow.Cells["pmnt_mode_revised"].Value = " ";
                DataGridViewComboBoxCell cbcell = new DataGridViewComboBoxCell();
                DataTable tbl = bao.get_Paymode_revised();
                cbcell.DataSource = tbl;
                cbcell.DisplayMember = "kind_pment";
                cbcell.ValueMember = "kind_pment";
                cbcell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                dtgUnsubmit.CurrentRow.Cells["pmnt_mode_revised"] = cbcell;                
            }
            else if (curCol.Name == "Receptionist")
            {
                DataGridViewComboBoxCell cbcell = new DataGridViewComboBoxCell();
                DataTable tbl = bao_rcpt.get_lst_Receptionist();
                cbcell.DataSource = tbl;
                cbcell.DisplayMember = "recept_name";
                cbcell.ValueMember = "recept_name";
                cbcell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                //dtgUnsubmit.CurrentRow.Cells["Receptionist"] = cbcell;
                try
                {
                    DataRow[] tt = tbl.Select("recept_name='" + dtgSubmit.CurrentRow.Cells["Receptionist"].Value.ToString() + "'");
                    if (tt.Length > 0)
                        dtgSubmit.CurrentRow.Cells["Receptionist"] = cbcell;
                    else
                    {
                        dtgSubmit.CurrentRow.Cells["Receptionist"].Value = ' ';
                        dtgSubmit.CurrentRow.Cells["Receptionist"] = cbcell;
                    }
                }
                catch (Exception ex)
                {
                    colIdxs.Add(dtgSubmit.CurrentCell.ColumnIndex);
                }
            }
            else if (IsTextBoxColumn(e.ColumnIndex))
            {
                DataGridViewTextBoxCell txtcell = new DataGridViewTextBoxCell();
                dtgUnsubmit.CurrentRow.Cells["VAT_number_revised"] = txtcell;
                dtgUnsubmit.CurrentRow.Cells["VAT_number_revised"].ReadOnly = false;
            }
        }

        private void dtgSubmit_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //if (dtgSubmit.RowCount == 0)
            //    return;

            //DataGridViewColumn curCol = dtgSubmit.CurrentCell.OwningColumn;
            ////if (IsComboBoxColumn(e.ColumnIndex) == true && curCol.Name == "pmnt_mode_revised")
            //if (curCol.Name == "pmnt_mode_revised")
            //{
            //    if (pmt_rev == "")
            //    {
            //        pmt_rev = dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].Value.ToString();
            //    }
            //    dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].Value = " ";
            //    DataGridViewComboBoxCell cbcell = new DataGridViewComboBoxCell();
            //    DataTable tbl = bao.get_Paymode_revised();
            //    cbcell.DataSource = tbl;
            //    cbcell.DisplayMember = "kind_pment";
            //    cbcell.ValueMember = "kind_pment";
            //    cbcell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            //    dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"] = cbcell;
            //    dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].ReadOnly = false;
            //}
            //else
            //    //if (IsComboBoxColumn(e.ColumnIndex) == true && curCol.Name == "Receptionist")
            //    if (curCol.Name == "Receptionist")
            //    {
            //        DataGridViewComboBoxCell cbcell = new DataGridViewComboBoxCell();
            //        DataTable tbl = bao_rcpt.get_lst_Receptionist();
            //        cbcell.DataSource = tbl;
            //        cbcell.DisplayMember = "recept_name";
            //        cbcell.ValueMember = "recept_name";
            //        cbcell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            //        //dtgSubmit.CurrentCell.OwningRow.Cells.RemoveAt(e.ColumnIndex);
            //        try
            //        {
            //            DataRow[] tt = tbl.Select("recept_name='" + dtgSubmit.CurrentRow.Cells["Receptionist"].Value.ToString() + "'");
            //            if (tt.Length > 0)
            //                dtgSubmit.CurrentRow.Cells["Receptionist"] = cbcell;
            //            else
            //            {
            //                dtgSubmit.CurrentRow.Cells["Receptionist"].Value = ' ';
            //                dtgSubmit.CurrentRow.Cells["Receptionist"] = cbcell;
            //            }
            //        }
            //        catch (Exception ex)
            //        {
            //            colIdxs.Add(dtgSubmit.CurrentCell.ColumnIndex);
            //        }
            //    }
            //    else if (IsTextBoxColumn(e.ColumnIndex))
            //    {
            //        DataGridViewTextBoxCell txtcell = new DataGridViewTextBoxCell();
            //        txtcell.MaxInputLength = 5;
            //        dtgSubmit.CurrentRow.Cells["VAT_number_revised"] = txtcell;
            //        dtgSubmit.CurrentRow.Cells["VAT_number_revised"].ReadOnly = false;
            //    }
        }

        private void dtgSubmit_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dtgSubmit.RowCount == 0)
                return;

            DataGridViewColumn curCol = dtgSubmit.CurrentCell.OwningColumn;
            //if (IsComboBoxColumn(e.ColumnIndex) == true && curCol.Name == "pmnt_mode_revised")
            if (curCol.Name == "pmnt_mode_revised")
            {
                //if (pmt_rev == "")
                //{
                //    pmt_rev = dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].Value.ToString();
                //}
                //dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].Value = " ";
                DataGridViewComboBoxCell cbcell = new DataGridViewComboBoxCell();
                DataTable tbl = bao.get_Paymode_revised();
                cbcell.DataSource = tbl;
                cbcell.DisplayMember = "kind_pment";
                cbcell.ValueMember = "kind_pment";
                cbcell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"] = cbcell;
                dtgSubmit.CurrentRow.Cells["pmnt_mode_revised"].ReadOnly = false;
            }
            else
                //if (IsComboBoxColumn(e.ColumnIndex) == true && curCol.Name == "Receptionist")
                if (curCol.Name == "Receptionist")
                {
                    DataGridViewComboBoxCell cbcell = new DataGridViewComboBoxCell();
                    DataTable tbl = bao_rcpt.get_lst_Receptionist();
                    cbcell.DataSource = tbl;
                    cbcell.DisplayMember = "recept_name";
                    cbcell.ValueMember = "recept_name";
                    cbcell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                    //dtgSubmit.CurrentCell.OwningRow.Cells.RemoveAt(e.ColumnIndex);
                    try
                    {
                        DataRow[] tt = tbl.Select("recept_name='" + dtgSubmit.CurrentRow.Cells["Receptionist"].Value.ToString() + "'");
                        if (tt.Length > 0)
                            dtgSubmit.CurrentRow.Cells["Receptionist"] = cbcell;
                        else
                        {
                            dtgSubmit.CurrentRow.Cells["Receptionist"].Value = ' ';
                            dtgSubmit.CurrentRow.Cells["Receptionist"] = cbcell;
                        }
                    }
                    catch (Exception ex)
                    {
                        colIdxs.Add(dtgSubmit.CurrentCell.ColumnIndex);
                    }
                }
                else if (IsTextBoxColumn(e.ColumnIndex))
                {
                    DataGridViewTextBoxCell txtcell = new DataGridViewTextBoxCell();
                    txtcell.MaxInputLength = 5;
                    dtgSubmit.CurrentRow.Cells["VAT_number_revised"] = txtcell;
                    dtgSubmit.CurrentRow.Cells["VAT_number_revised"].ReadOnly = false;
                }
        }       
    }
}